package cn.edu.lingnan.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.edu.lingnan.dao.ConsumerDao;
import cn.edu.lingnan.model.Consumer;
import cn.edu.lingnan.model.PageBean;
import cn.edu.lingnan.util.DbUtil;
import cn.edu.lingnan.util.JsonUtil;
import cn.edu.lingnan.util.ResponseUtil;
import cn.edu.lingnan.util.StringUtil;

public class ConsumerSaveServlet extends HttpServlet{
	DbUtil dbUtil=new DbUtil();
	ConsumerDao consumerDao=new ConsumerDao();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String consumerName=request.getParameter("consumerName");
		String password=request.getParameter("password");
		String id=request.getParameter("id");
		Consumer consumer=new Consumer(consumerName,password);
		if(StringUtil.isNotEmpty(id)){
			consumer.setId(Integer.parseInt(id));
		}
		Connection con=null;
		try{
			con=dbUtil.getCon();
			int saveNums=0;
			JSONObject result=new JSONObject();
			if(StringUtil.isNotEmpty(id)){
				saveNums=consumerDao.consumerModify(con, consumer);
			}else{
				saveNums=consumerDao.consumerAdd(con, consumer);
			}
			if(saveNums>0){
				result.put("success", "true");
			}else{
				result.put("success", "true");
				result.put("errorMsg", "保存失败");
			}
			ResponseUtil.write(response, result);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
	
}
